package com.padakeji.android.pworks.module.version.view;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DownloadManager;
import android.content.DialogInterface;
import android.net.Uri;
import android.os.Bundle;
import android.app.DialogFragment;
import android.view.ContextThemeWrapper;
import android.widget.Toast;
import com.padakeji.android.pworks.R;
import com.padakeji.android.pworks.module.version.VersionController;
import com.padakeji.android.pworks.module.version.entity.VersionInfo;

public class UpdateDialogFragment extends DialogFragment {

	public static UpdateDialogFragment newInstance(VersionInfo newVersionInfo) {
		UpdateDialogFragment frag = new UpdateDialogFragment();

		Bundle args = new Bundle();
		args.putInt(VersionController.ARGS_KEY_VERSION_CODE, newVersionInfo.versionCode);
		args.putString(VersionController.ARGS_KEY_VERSION_NAME, newVersionInfo.versionName);
		args.putString(VersionController.ARGS_KEY_DOWNLOAD_LINK, newVersionInfo.downloadLink);
		args.putString(VersionController.ARGS_KEY_RELEASE_NOTES, newVersionInfo.releaseNotes);

		frag.setArguments(args);

		return frag;
	}

	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		int versionCode = getArguments().getInt(VersionController.ARGS_KEY_VERSION_CODE, 0);
		String versionName = getArguments().getString(VersionController.ARGS_KEY_VERSION_NAME, "");
		String downloadLink = getArguments().getString(VersionController.ARGS_KEY_DOWNLOAD_LINK, "");
		String releaseNotes = getArguments().getString(VersionController.ARGS_KEY_RELEASE_NOTES, "");

		String title = "版本更新" + versionName;

		return new AlertDialog.Builder(new ContextThemeWrapper(getActivity(), getTheme()))
				.setTitle(title)
				.setMessage(releaseNotes)
				.setPositiveButton("马上更新", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
                        DownloadManager downloadManager =(DownloadManager)getActivity().getSystemService(getActivity().DOWNLOAD_SERVICE);
						Uri uri = Uri.parse("http://padady.com:8001/apks/LockScreen.apk");
						DownloadManager.Request request = new DownloadManager.Request(uri);
						request.setDestinationInExternalPublicDir("pWorks/apks", "LockScreen.apk");
						request.setTitle("一键锁屏");
						request.setDescription("一键锁屏描述");
						request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
						long reference = downloadManager.enqueue(request);
					}
				})
				.setNegativeButton("暂不更新", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
					}
				})
				.create();
	}

	@Override
	public void onDismiss(DialogInterface dialog) {
		super.onDismiss(dialog);
		getActivity().finish();
	}
}
